<template>
    <section class="content">
        <Panel :expandable="false" :expand="true">
            <template slot="title">预审查询</template>
            <template slot="body">
                <el-form ref="form" :rules="rules" :model="this" label-width="100px">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="店铺收款账户">
                                <el-select v-model="receiverNumber" class="full-cell">
                                    <el-option v-for="s in shopList" :label="s" :key="s" :value="s"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="总额" prop="applyTotalAmount" label-width="60px">
                                <el-input v-model.number="applyTotalAmount">
                                    <template slot="append">USD</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-form-item label="订单日期" label-width="70px">
                                <el-date-picker
                                    v-model="orderDate"
                                    :type="datetimeType"
                                    :value-format="datetimeValueFormat"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    class="full-cell"
                                    >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                          <el-form-item label="疑点" label-width="60px">
                            <el-switch v-model="doubt" active-value="1" inactive-value="0">
                            </el-switch>
                          </el-form-item>
                        </el-col>
                        <el-col :span="2" style="padding-left: 25px">
                            <el-button @click="handleSearch" type="success">搜索</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </template>
        </Panel>
        <Panel :expandable="false" :expand="true" :hasTitle="false">
            <template slot="body">
                <el-form label-width="70px" style="padding: 5px 0 20px 0;">
                    <el-row :gutter="12">
                        <el-col :span="7">
                            <el-form-item label="订单编号">
                                <el-input v-model="orderNumber" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="success" @click="handleSearchByOrderNumber">搜索</el-button>
                            <el-button type="primary" :disabled="buttondisabled" @click="handleCommit">提交预审</el-button>
                        </el-col>
                        <el-col :span="6" style="text-align: right">
                            <div style="padding-top: 10px">总金额：{{totalAmount}}</div>
                        </el-col>
                    </el-row>
                </el-form>

                <el-table :data="subList" header-row-class-name="header-class">
                    <el-table-column label="订单编号" align="center">
                        <template slot-scope="scope">
                            <span :style="{'color': scope.row.isInResult? 'red': ''}">{{scope.row.orderId}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="orderCreated" label="订单日期"></el-table-column>
                    <el-table-column align="center" prop="total" label="订单金额"></el-table-column>
                    <el-table-column align="center" prop="total" label="状态" :formatter = "stateFormat"></el-table-column>
                    <el-table-column align="center" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" icon="iconfont rticon-shanchu" @click="handleDelete(scope.row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="clear-fix">
                    <el-pagination
                        style="float: right; margin-top: 20px;"
                        background
                        layout="total, prev, pager, next"
                        @current-change="handleCurrentChange"
                        @prev-click="handlePrev"
                        @next-click="handleNext"
                        :current-page="searchParam.page"
                        :page-size="searchParam.rows"
                        :total="searchParam.total">
                    </el-pagination>
                </div>
            </template>
        </Panel>

        <el-dialog title="预审" :visible.sync="visible" :append-to-body="true">
            <el-form :model="form">
                <el-form-item label="申请名称" :label-width="formLabelWidth">
                    <el-input v-model="applyName" auto-complete="off" placeholder="请输入申请名称"></el-input>
                </el-form-item>
                <!--<el-form-item label="人工甄别" :label-width="formLabelWidth">-->
                    <!--<el-switch-->
                        <!--v-model="isMatch"-->
                        <!--active-color="#13ce66"-->
                        <!--inactive-color="gray">-->
                    <!--</el-switch>-->
                <!--</el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer" style="padding-bottom: 20px;">
                <el-button type="primary" @click="save">确 定</el-button>
                <el-button @click="visible = false">取 消</el-button>
            </div>
            </el-dialog>
    </section>
</template>
<script>
import Panel from '@/components/common/panel'
import instance from '@/api/index.js'
import apiUrls from '@/js/common/apiUrls'
import {floatAdd, datetimeType, datetimeValueFormat} from '@/js/util'

export default {
    name: "preaudit",
    components: {
        Panel
    },
    data() {
        return {
            datetimeType: datetimeType,
            datetimeValueFormat: datetimeValueFormat,
            // datetimeValueFormat: "yyyy-MM-dd HH:mm:ss",
            list: [],
            subList: [],
            deletedList: [],
            receiverNumber: "",
            orderDate: "",
            orderNumber: "",
            searchParam: {
                page: 1,
                total: 0,
                rows: 10
            },
            shopList: [],
            applyTotalAmount: "",
            // totalAmount: "",
            rules: {
                applyTotalAmount: [{
                    required: true,
                    type: "number",
                    message: "申报金额必填！",
                    trigger: "blur"
                }],
            },
            applyName: "",
            isMatch: false,
            formLabelWidth: '120px',
            visible: false,
            doubt: 0,
            doubtState: '疑点',
            buttondisabled: true,
        };
    },
    methods: {
        stateFormat(row, column) {
          // console.log(row.total)
          // console.log(row.status)
          // console.log(row.status === null)
          if(this.doubtState === '非疑点') {
            if(row.status === "0") {
              return '通过';
            }else if(row.status === "1") {
              return '疑点';
            }else if(row.status === "2") {
              return '异常';
            }else if(row.status === "3") {
              return '审核失败';
            }else if(row.status === "4") {
              return '人工审核处理中';
            }else {
              return '';
            }
          }
          // console.log(this.doubt === '0')
          // if (this.doubt === '0') {
          //   return '非疑点'
          // } else {
          //   return '疑点'
          // }
          return this.doubtState
        },
        padding(n) {
            if(n < 10) {
                return "0" + n;
            } else {
                return "" + n;
            }
        },
        getDateStr(date) {
            if(date) {
                return date.getFullYear() + "-" + this.padding(date.getMonth()+1) + "-" + this.padding(date.getDate());
            }
        },
        handleSearch() {
            let self = this;
            console.log('1111111111111')
            console.log(self.doubt)
            if(self.doubt === '0') {
              self.doubtState = '非疑点'
            }else{
              self.doubtState = '疑点'
            }
            this.$refs.form.validate((valid)=>{
                if(!valid) {
                    return;
                }
                // this.begin = this.getDateStr(this.orderDate && this.orderDate[0]);
                // this.end = this.getDateStr(this.orderDate && this.orderDate[1]);
                this.begin = this.orderDate && this.orderDate[0];
                this.end = this.orderDate && this.orderDate[1];

                let param = Object.assign({
                    account: this.receiverNumber || null,
                    begin: this.begin||null,
                    end: this.end||null,
                    total: this.applyTotalAmount,
                    isMatch: this.doubt
                });

                instance({
                    method: 'post',
                    url: apiUrls.receive.orderList,
                    params: param
                }).then(function (data) {
                    if(data.data.success){
                        self.list = data.data.data;
                        self.handleSearchByOrderNumber();
                        self.deletedList = [];
                        self.buttondisabled = self.list.length> 0? false: true;
                    }
                }).catch(function (err) {
                    console.log(err)
                });
            });
        },

        handleSearchByOrderNumber() {
            this.searchParam.page =  1;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },

        searchInList(orderNumber, pageIndex) {
            console.log("orderId: ", orderNumber, ", page: ", pageIndex);
            let tempList = [];
            this.list.forEach(function(item) {
                item.isInResult = false;
            });
            if(orderNumber == undefined || orderNumber == '') {
                tempList = this.list.slice();
            } else {
                tempList = this.list.filter((o)=>{
                    return o.orderId.toLowerCase().indexOf(orderNumber.toLowerCase()) > -1;
                });
                tempList.forEach(function(item) {
                    item.isInResult = true;
                });
                console.log("before: ", tempList);
                tempList = tempList.concat(this.list.filter((o)=>{
                    return o.orderId.toLowerCase().indexOf(orderNumber.toLowerCase()) === -1;
                }));
                console.log("after: ", tempList);
            }

            let pageSize = this.searchParam.rows;
            let total = tempList.length;

            let subList = tempList.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
            console.log("sl: ", subList);
            return {
                total: total,
                list: subList
            };

        },

        handleDelete(item) {
            for(let i = 0; i < this.list.length; i++) {
                if(this.list[i].orderId === item.orderId) {
                    this.list.splice(i, 1);
                }
            }

            for(let i = 0; i < this.subList.length; i++) {
                if(this.subList[i].orderId === item.orderId) {
                    this.subList.splice(i, 1);
                }
            }

            this.deletedList.push(item.orderId);

            if(this.searchParam.total - 1 <= (this.searchParam.page - 1) * this.searchParam.rows) {
                this.handleCurrentChange(this.searchParam.page - 1);
            } else {
                this.handleCurrentChange(this.searchParam.page);
            }
        },

        handleCurrentChange(pageIndex) {
            this.searchParam.page = pageIndex;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },
        handleNext(pageIndex) {
            this.searchParam.page = pageIndex;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },
        handlePrev(pageIndex) {
            this.searchParam.page = pageIndex;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },

        getCurrentDateStr() {
            let now = new Date();
            return now.getFullYear() + this.padding(now.getMonth()+1) + this.padding(now.getDate()) + this.padding(now.getHours()) + this.padding(now.getMinutes()) + this.padding(now.getSeconds());
        },

        // 提交审核
        handleCommit() {
            let self = this;
            this.applyName = this.getCurrentDateStr();
            this.isMatch = true;
            this.visible = true;
            // this.$prompt('请输入申请名称', '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     inputValue: this.getCurrentDateStr()
            // }).then(({ value }) => {
            //     let param = {
            //         account: this.receiverNumber,
            //         begin: this.begin,
            //         end: this.end,
            //         applyName: value,
            //         total: this.applyTotalAmount,
            //         deleteOrders: this.deletedList.join(',')
            //     };
            //     instance({
            //         method: 'post',
            //         url: apiUrls.receive.preauditCommit,
            //         data: param
            //     }).then(function (data) {
            //         if(data.data.success){
            //             self.$emit('commited');
            //         } else {
            //             // 失败
            //         }
            //     }).catch(function (err) {
            //         console.log(err)
            //     });
            // }).catch(() => {

            // });
        },
        save() {
            if(this.applyName==='' || this.applyName == null) {
                this.$alert("请输入申请名称！");
                return;
            }
            let self = this;
                let param = {
                    account: this.receiverNumber,
                    begin: this.begin,
                    end: this.end,
                    applyName: this.applyName,
                    // isMatch: this.isMatch?1:0,
                    isMatch: this.doubt,
                    total: this.applyTotalAmount,
                    deleteOrders: this.deletedList.join(',')
                };
                instance({
                    method: 'post',
                    url: apiUrls.receive.preauditCommit,
                    data: param
                }).then(function (data) {
                    if(data.data.success){
                        self.$emit('commited', data.data.msg);
                        self.visible = false;
                    } else {
                        // 失败
                        self.$emit('commited', false);// 失败也要求关闭弹框
                        self.visible = false;
                    }
                }).catch(function (err) {
                    self.$emit('commited', false);// 失败也要求关闭弹框
                    self.visible = false;
                });
        },

        // 获取店铺
        getShopList(cb) {
            let self = this;
            let param = {
                    id: "0"
                };
                instance({
                    method: 'post',
                    url: apiUrls.receive.shopList,
                    data: param
                }).then(function (data) {
                    self.shopList = data.data.data || [];
                    if(data && data.data && data.data.data && data.data.data.length > 0) {
                        let shops = {};
                        data.data.data.forEach(function(s) {
                            let accounts = s.accounts;
                            accounts && accounts.forEach(function(a) {
                                shops[a] = a;
                            });
                        });
                        let arrShops = [];
                        for(let s in shops) {
                            arrShops.push(s);
                        }
                        self.shopList = arrShops;
                        self.receiverNumber = arrShops[0];
                        // self.handleSearch();
                    } else {
                        self.$error("授权店铺列表为空");
                    }
                }).catch(function (err) {
                    console.log(err)
                });
        },

        // 判断是否搜索的，给高亮
        isInResult(item) {
            if(this.orderNumber == null || this.orderNumber == '') {
                return false;
            }

            return item.orderId.toLowerCase().indexOf(this.orderNumber.toLowerCase()) > -1;
        }
    },
    computed: {
        totalAmount() {
            if(this.list && this.list.length) {
                let total = floatAdd(this.list.map((item)=>{
                    return item.total;
                }));

                return total;
            }

            return '';
        }
    },
    watch: {
        list() {
            console.log('list change...');
        }
    },
    created() {
        // console.log("created...");
        // window.xxx = this;
        // this.handleSearch();
        this.getShopList();
    }
}
</script>
<style scoped>
.el-date-editor {
    width: 100%;
}

.el-range-separator {
    width: 22px!important;
}

.el-form-item {
  margin-bottom: 2px;
}
</style>
